# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt


import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSAcceptanceSettlement(Document):
	# 保存前自动计算维修完成时间
	def before_save(self):
		sum_amount_no_tax = 0
		if self.parts_item: 
			for item in self.parts_item: #遍历子表行记录
				item.amount_no_tax = item.qty * item.price_no_tax
				sum_amount_no_tax = sum_amount_no_tax + item.qty * item.price_no_tax
		self.total_cost = self.labor_cost + sum_amount_no_tax + self.other_cost # 求和并赋值total_cost
		self.material_cost = sum_amount_no_tax	# 赋值material_cost

	
	def before_insert(self):
		# A路线校验:一个故障维修单不能有2个非取消状态验收结算单
		if self.ems_fault_repair and frappe.db.exists({"doctype": self.doctype, "ems_fault_repair": self.ems_fault_repair, "docstatus": ["in", (0,1)] }):
			frappe.throw(_("EMS Acceptance Settlement Is Created. The BillNo is:{0}").format(frappe.db.exists({"doctype": self.doctype, "ems_fault_repair": self.ems_fault_repair, "docstatus": ["in", (0,1)] })))
		# B路线校验:一个外部维修单不能有2个非取消状态验收结算单
		if self.ems_external_maintenance and frappe.db.exists({"doctype": self.doctype, "ems_external_maintenance": self.ems_external_maintenance, "docstatus": ["in", (0,1)] }):
			frappe.throw(_("EMS Acceptance Settlement Is Created. The BillNo is:{0}").format(frappe.db.exists({"doctype": self.doctype, "ems_external_maintenance": self.ems_external_maintenance, "docstatus": ["in", (0,1)] })))
		# 验收结算单要不是A路线, 要不是B路线
		if not self.ems_fault_repair and not self.ems_external_maintenance:
			frappe.throw("验收结算单必须来源于'故障维修单'或'外部维修单'两者其中之一!不允许两者为空!")

	def on_submit(self):
		# 更新卡片管理状态为normal useing
		frappe.db.set_value('EMS Equipment Card', self.equipment_number, {'card_manager_status': 'normal useing'})


	# 故障维修保存时更新故障报修之状态
	# def after_insert(self):
	# 	frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()


	# 故障维修删除时更新故障报修之状态
	# def after_delete(self):
	# 	frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()

	# 故障维修取消时更新故障报修之状态
	# def on_cancel(self):
	# 	frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()
